<?php
/*
** 360cps系统对接的处理类
*/

/*
** 反馈订单的操作类
*/
class Cps360Order
{
	protected $_db;

	public function __construct()
	{/*{{{*/
		$this->_name = __CLASS__  ;
		$this->_db = Db::getInstance( Config::$localDb );
	}/*}}}*/

	/*
	** 获取表名
	*/
	public function tableName()
	{
		return "cps360_order";
	}

	/*
	** 根据ID获取反馈订单信息
	*/
	public function getOne($id)
	{
		$sql = 'select * from ' . $this->tableName() . " where id=" . $id;
		$rst = $this->_db->query($sql);
		return $rst ? $rst->fetch() : array();
	}

	/*
	** 添加
	*/
	public function insert(&$data)
	{
		$ok = $this->_db->insert($this->tableName(), array($data));
		if ($ok) {
			$rst = $this->_db->query("SELECT LAST_INSERT_ID()");
			$data['id'] = $rst ? (int)$rst->fetchColumn() : 0;
		}

		return $ok;
	}

	/*
	** 获取列表
	*/
	public function getList($page=0, $size=20, $where="", $order='id')
	{
		$sql = 'select * from ' . $this->tableName();
		if ($where) $sql .= ' where ' . $where;
		if ($order) $sql .= ' order by ' . $order;

		$start = $page * $size;
		$sql .= ' limit ' . $start . ',' . $size;
		$rst = $this->_db->query($sql);
		return $rst ? $rst->fetchAll() : array();
	}

	/*
	** 获取数量
	*/
	public function getCount($where="")
	{
		$sql = 'select count(*) from ' . $this->tableName();
		if ($where) $sql .= ' where ' . $where;
		$rst = $this->_db->query($sql);
		return $rst ? (int)$rst->fetchColumn() : 0;
	}

    /*
     * 商品URL TODO
     */
    public function getGoodsUrl($goods_id)
    {
        return "/merchant/goods.php?type=one&id=".$goods_id;
    }

    /*  
     * 获取分类路径，如：一级分类_二级分类...(_N级分类)..._当前分类 TODO
     */
    public function getCatePathnames($id)
    {   
        $cate_mng = new MerchantCate();

        $count = $cate_mng->getCount();
        if (!$count) return "";

        $cate_list = array();
        $list = $cate_mng->getList(0, $count);
        foreach ($list as $row)
        {
            $cate_list[$row['id']] = $row;
        }

        $name_list = array();
        $current_id = $id;
        while ($current_id) {
            $cate_info = $cate_list[$current_id];
            $name_list[] = $cate_info['name'];

            $current_id = $cate_info['pid'];
        }

        $name_list = array_reverse($name_list);
        return implode('_', $name_list);
    } 

    /*
     * 根据分类ID得到分成比例 TODO
     */
    public function getCommPercent($id)
    { 
        global $cps360_comm_list;
        $cate_mng = new MerchantCate();

        $count = $cate_mng->getCount();
        if (!$count) return $cps360_comm_list[0];//默认分成比例

        $cate_list = array();
        $list = $cate_mng->getList(0, $count);
        foreach ($list as $row)
        {
            $cate_list[$row['id']] = $row;
        }

        $current_id = $id;
        while ($current_id) {
            if (array_key_exists($current_id, $cps360_comm_list))
                return $cps360_comm_list[$current_id];

            $current_id = $cate_list[$current_id]['pid'];
        }

        return $cps360_comm_list[0];
    }

	/*
	** 格式化订单，转换成360CPS系统所需的反馈订单
    ** TODO
	*/
	public function formatOrder($order_info)
    {
        global $cps360_comm_list;

		$goods_mng = new MerchantGoods();
		$cate_mng = new MerchantCate();

		$total_comm = 0;
		$commission = array();
		$p_info = array();
		
		$detail_list = unserialize($order_info['detail']);
		foreach ($detail_list as $detail) {
			list($goods_id, $name, $cid, $price, $num) = $detail;

            $goods_url = $this->getGoodsUrl($goods_id);//商品地址
            $cate_paths = $this->getCatePathnames($cid);//分类路径
            $comm_percent =  $this->getCommPercent($cid);//该分类的分成比例

			$comm_price = $price*$num*$comm_percent*0.01;
			$total_comm += $comm_price;
			$commission[] = $cid.','.$comm_percent.','.$comm_price.','.$price.','.$num;
			$p_info[] = $cid.','.$name.','.$goods_id.','.$price.','.$num.','.$cate_paths.','.urlencode($goods_url);
		}

		$format_order = array();
		$format_order['order_id'] = $order_info['id'];
		$format_order['order_time'] = date("Y-m-d H:i:s", $order_info['order_time']);
		$format_order['order_updtime'] = date("Y-m-d H:i:s", $order_info['updtime']);

		$format_order['total_comm'] = $total_comm;
		$format_order['commission'] = implode("|", $commission);
		$format_order['p_info'] = implode("|", $p_info);

		$format_order['server_price'] = $order_info['server_price'];
		$format_order['order_price'] = $order_info['order_price'];
		$format_order['coupon'] = $order_info['coupon'];
		$format_order['total_price'] = $order_info['total_price'];
		$format_order['status'] = $order_info['status'];

		return $format_order;
	}

	public function formatOrderById($order_id)
	{
		$order_mng = new MerchantOrder();

		$order_info = $order_mng->getOne($order_id);
		if (!$order_info)
			return array();

		return $this->formatOrder($order_info);
	}

	/*
	** 格式化反馈订单信息
	*/
	public function formatOne($data)
	{
		$order_data = $this->formatOrderById($data['order_id']);
		$data = array_merge($data, $order_data);
		return $data;
	}

	/*
	** 获取格式化的反馈订单列表
	*/
	public function formatList($list)
	{
		foreach ($list as &$row) {
			$row = $this->formatOne($row);
		}
		return $list;
	}

	/*
     ** 获取列表
     ** TODO
	*/
	public function getFormatList($page=0, $size=20, $where="", $order='id')
	{
		$sql = "select a.bid,a.order_id,a.qid,a.qihoo_id,a.ext,b.* from cps360_order as a,merchant_order as b where a.order_id=b.id " . $where;
		if ($order) $sql .= ' order by ' . $order;

		$start = $page * $size;
		$sql .= ' limit ' . $start . ',' . $size;
		$rst = $this->_db->query($sql);
		$list = $rst ? $rst->fetchAll() : array();

		if (!$list) return array();

		foreach ($list as &$row) {
			$tmp = $this->formatOrder($row);
			$row = array_merge($row, $tmp);
		}
		return $list;
	}

	/*
     ** 获取数量
     ** TODO
	*/
	public function getFormatCount($where="")
	{
		$sql = "select count(*) from cps360_order as a,merchant_order as b where a.order_id=b.id " . $where;
		$rst = $this->_db->query($sql);
		return $rst ? (int)$rst->fetchColumn() : 0;
	}

	/*
	** 将订单信息反馈给360CPS系统
	*/
	public function feedback($id)
	{
		$data = $this->getOne($id);
		if (!$data)
			return false;

		$order_id = $data['order_id'];
		$order_info = $this->formatOrderById($order_id);
		if (!$order_info)
			return false;

		$now_time = time();
		$feedback_info = $order_info;
		$feedback_info['bid'] = $data['bid'];
		$feedback_info['qihoo_id'] = $data['qihoo_id'];
		$feedback_info['qid'] = $data['qid'];
		$feedback_info['ext'] = $data['ext'];
		$feedback_info['atice_time'] = $now_time;
		$feedback_info['sign'] =  md5($feedback_info['bid'].'#'.$feedback_info['active_time'].'#'.CPS360_CP_KEY);
		$active_status = curlRequest(CPS360_INRECORD_URL, $feedback_info); // 反馈订单给360cps系统

		$sql = "update " . $this->tableName() . " set active_time='" . $now_time . "', active_status='" . $active_status . "' where id=" . $id;
		$ok = $this->_db->query($sql);// 保存反馈结果
		return $active_status;
	}
    
    /*
     * 返回订单的查询语句
     * TODO
     */
    public function getQueryWhere($post)
    {
        $now_time = time();
        $where = "";

        $order_id = trim($post['order_id']);
        if ($order_id) {
            $where .= " and a.order_id = '" . $order_id . "'";
        }

        $last_order_id = trim($post['last_order_id']);
        if ($last_order_id) {
            $where .= " and a.order_id > '" . $last_order_id . "'";
        }

        // 下单时间
        $start_time = $post['start_time'] ? strtotime($post['start_time']) : 0;
        if ($start_time) {
            $where .= " and b.order_time >= '" . $start_time . "'";
        }
        $end_time = $post['end_time'] ? strtotime($post['end_time']) : 0;
        if ($post['end_time']) {
            $where .= " and b.order_time < '" . $end_time . "'";
        }

        // 订单最后修改时间
        $updstart_time = $post['updstart_time'] ? strtotime($post['updstart_time']) : 0;
        if ($post['updstart_time']) {
            $where .= " and b.update_time >= '" . $updstart_time . "'";
        }
        $updend_time = $post['updend_time'] ? strtotime($post['updend_time']) : 0;
        if ($post['updend_time']) {
            $where .= " and b.update_time < '" . $updend_time . "'";
        }

        return $where;
    }

    /* 
     * 返回查询订单的数量
     */
    public function getQueryCount($post)
    {
        $where = $this->getQueryWhere($post);
        return $this->getFormatCount($where);
    }

    /*
     * 返回查询订单的数据
     */
    public function getQueryList($post, $start, $size)
    {
        $where = $this->getQueryWhere($post);
        return $this->getFormatList($start, $size, $where, 'a.order_id');
    }

    /*
     * 返回对账订单的查询语句
     * TODO
     */
    public function getCheckWhere($post)
    {
        $where = "";
        //$where .= " and b.status=5"; // 对账只需要已完成的订单
        
        $last_order_id = trim($post['last_order_id']);
        if ($last_order_id) {
            $where .= " and a.order_id > '" . $last_order_id . "'";
        }

        //默认返回本月的订单数据
        $bill_month = $post['bill_month'] ? trim($post['bill_month']) : date("Y-m");
        list($year, $month) = explode("-", $bill_month);
        if ($month == 12)
        {
            $year = (int)$year + 1;
            $month = 1;
        } else {
            $month = (int)$month + 1;
        }
        $start_time = strtotime($bill_month."-01 00:00:00");
        $end_time = strtotime($year."-".$month."-01 00:00:00");
        $where .= " and b.order_time >= '" . $start_time . "'";
        $where .= " and b.order_time < '" . $end_time . "'";

        return $where;
    }

    /* 
     * 返回对账订单的数量
     */
    public function getCheckCount($post)
    {
        $where = $this->getCheckWhere($post);
        return $this->getFormatCount($where);
    }

    /*
     * 返回对账订单的数据
     */
    public function getCheckList($post, $start, $size)
    {
        $where = $this->getCheckWhere($post);
        return $this->getFormatList($start, $size, $where, 'a.order_id');
    }

}
?>
